from Server.Handler._BaseHandler import BaseHandler, record_http_request
from Server.Handler.JsonResponse import JsonResponse
from Server.GlobalConfig import Driver
import json


class ServerGetHandler(BaseHandler):

    @record_http_request
    def get(self, *args, **kwargs):
        result = JsonResponse()
        result.set_data_item(args[0], getattr(Driver, 'get_' + args[0])(args[1]))
        self.write(result.to_str())


class ConnectHandler(BaseHandler):

    @record_http_request
    def post(self, *args, **kwargs):
        data = json.loads(self.request.body)
        result = JsonResponse()
        prefix = self.request.uri.split('/api/v1/')[-1].split('/')[0]
        func_name = Driver.function_support(prefix, args)
        if 'devices' in data:
            for ser in data['devices']:
                driver = Driver.get_driver(ser, data['platform'])
                getattr(driver, func_name)()
        else:
            driver = Driver.get_driver(platform=data['platform'])
            getattr(driver, func_name)()
        result.set_data_item('sessions', Driver.get_sessions(data['platform']))
        self.write(result.to_str())


class ServerPostHandler(BaseHandler):

    @record_http_request
    def post(self, *args, **kwargs):
        result = JsonResponse()
        data = json.loads(self.request.body)
        prefix = self.request.uri.split('/api/v1/')[-1].split('/')[0]
        func_name = Driver.function_support(prefix, args)
        driver = Driver.get_driver(args[0])
        data = Driver.build_args(func_name, data)
        ret = getattr(driver, func_name)(**data)
        result.set_data(ret)
        self.write(result.to_str())

    @record_http_request
    def get(self, *args, **kwargs):
        result = JsonResponse()
        prefix = self.request.uri.split('/api/v1/')[-1].split('/')[0]
        func_name = Driver.function_support(prefix, args)
        driver = Driver.get_driver(args[0])
        ret = getattr(driver, func_name)()
        result.set_data(ret)
        self.write(result.to_str())